﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ongoal.Quotation.Common
{
    /// <summary>
    /// 树结构表实体基类 
    /// </summary>
    public class TreeBase<T> : ModelBase
    {
        /// <summary>
        /// 无参构造函数
        /// </summary>
        public TreeBase():base()
        { 
        }
        /// <summary>
        /// 父节点ID 
        ///</summary>
        [SugarColumn(ColumnName = "ParentID")]
        public int? ParentID { get; set; }
        /// <summary>
        /// 继承路径 
        ///</summary>
        [SugarColumn(ColumnName = "PropPath")]
        public string? PropPath { get; set; }
        /// <summary>
        /// 组织结构层级 
        ///</summary>
        [SugarColumn(ColumnName = "NodeLevel")]
        public int? NodeLevel { get; set; }


        /// <summary>
        /// 是否已经删除
        ///</summary>
        [SugarColumn(ColumnName = "Deleted")]
        public int? Deleted { get; set; }

        /// <summary>
        /// 子节点列表
        /// </summary>
        [SugarColumn(IsIgnore = true)]
        public List<T>? Children { get; set; }

    }
    /// <summary>
    /// 
    /// </summary>
    public static class TreeCommon
    {
        /// <summary>
        /// 根据节点列表构建成树形（会忽略无法挂载在树上的非根节点）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input"></param>
        /// <param name="parentID">根节点</param>
        /// <returns></returns>
        public static List<T> BuildTree<T>(this List<T> input, int parentID) where T : TreeBase<T>, new()
        {
            var rootList = input.Where(t=>t.ParentID == parentID).ToList();
            foreach (var root in rootList)
            {
                var childrenList = input.Where(t => t.ParentID == root.ID).ToList();
                if (childrenList.Any())
                {
                    root.Children = input.BuildTree(root.ID);
                }
                else
                {
                    root.Children = null;
                }
            }
            return rootList;
        }
    }
}
